package com.linshidream.intrachat.simplenio.pipeline;

import com.linshidream.intrachat.simplenio.pipeline.context.MiniHandlerContext;
import com.linshidream.intrachat.simplenio.pipeline.handler.MiniChannelOutboundHandler;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * Created on 2025/8/19 18:21
 *
 * @author linshidream
 * @version 1.0.0
 * @description
 */

public class LengthFieldMessageEncoder implements MiniChannelOutboundHandler {
    @Override
    public void channelWrite(MiniHandlerContext ctx, Object msg) {

        if (!(msg instanceof String)) {
            ctx.fireWrite(msg);
            return;
        }

        System.out.println("[" + ctx.handlerName() + "],写数据到通道");

        String str = (String) msg;
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        ByteBuffer buf = ByteBuffer.allocate(4 + bytes.length);
        buf.putInt(bytes.length);
        buf.put(bytes);
        buf.flip();

        // 编码结束 往下一环传递
        ctx.fireWrite(buf);
    }
}
